/**************************************************************************//**
 * @file     xip_function.c
 * @version  V1.0.0
 * @author   sz414
 * @date     2021-02-22 PM
 * @brief    该文件包含了...
 * 
 * @copyright Copyright (C) 2020 Chipsea Technologies Corp. All rights reserved.
 *****************************************************************************/

// Include header file.
#include "uart.h"
#include <string.h>
#include "xip_function.h"
#include "clock.h"

#define DEFAULT_UART_BAUD   115200
__attribute__((used)) static const uint8 xip_reserved[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};


/**@brief 串口初始化
 * 
 * @param[in]  baud    配置串口波特率.
 * @param[in] tx_pin    串口发送口
 * @param[in] rx_pin    串口接受口
 * @return  none。
 */

void hal_uart_init(int baud, GpioPin_t tx_pin, GpioPin_t rx_pin)
{
    int pclk = clk_get_pclk();
    uint32_t dll;
    
    AP_UART_TypeDef * cur_uart = AP_UART0;
    per_module_t mod        = MOD_UART0;
    IRQn_Type irq_type  = UART0_IRQn;
    gpio_fmux_e fmux_tx    = FMUX_UART0_TX,     fmux_rx = FMUX_UART0_RX;

    hal_clk_gate_enable(mod);
    hal_clk_reset(mod);
    

  
    HalGpioPupdConfig(tx_pin, GPIO_PULL_UP);
    HalGpioPupdConfig(rx_pin, GPIO_PULL_UP);
    
    HalGpioFmuxConfig(tx_pin, fmux_tx);
    HalGpioFmuxConfig(rx_pin, fmux_rx);

    cur_uart->LCR =0;  
    dll = ((pclk>>4)+(baud>>1))/baud;
    cur_uart->MCR=0x0;
    cur_uart->LCR=0x80; 
    cur_uart->DLM=(dll & 0xFF00) >> 8;   
    cur_uart->DLL=(dll & 0xFF);   
   
    cur_uart->LCR = 0x03;  //8bit, 1 stop no parity    
    
    cur_uart->FCR= FCR_TX_FIFO_RESET|FCR_RX_FIFO_RESET|FCR_FIFO_ENABLE|UART_FIFO_RX_TRIGGER|UART_FIFO_TX_TRIGGER;    

        
    //enable Received Data Available Interrupt
    cur_uart->IER = IER_ERBFI;

	cur_uart->IER |= IER_PTIME;
	 
//	(*(uint32 *)(0x1fff0000 + (235 << 2)))   =   (uint32_t)&hal_UART0_IRQHandler;

    NVIC_SetPriority(irq_type, IRQ_PRIO_HAL);
    NVIC_EnableIRQ(irq_type);
    
}
